package pers.cz.mock;

import pers.cz.config.MybatisSqlSessionFactory;
import pers.cz.context.MyThreadLocals;
import pers.cz.entity.AutoCollectMethodParamsMapper;
import pers.cz.util.*;
import com.google.gson.Gson;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: postgirl-collection-client
 * @description: ParamsAndReturnMock
 * @author: Cheng Zhi
 * @create: 2022-03-02 09:31
 **/
public class ParamsAndReturnMybatisMock {

    private static RedisConfig redisUtil = null;

    static {
        redisUtil = new RedisConfig();
    }

    public static Object begin(Object targetMehod, Object object) {
        try {
            Gson gson = new Gson();
            System.out.println("------------监听到了入参------start---"/* + gson.toJson(object)*/);
            if (MyThreadLocals.methodContext.get() != null) {
                System.out.println("------cz------test-----从库里获取---");
                // 查数据库比对
                String myResponse = getResult(gson.toJson(targetMehod), gson.toJson(object));
                if (myResponse != null) {
                    System.out.println("------cz------test----获取到了---" /*+ myResponse*/);

                    return JsonUtil.jsonToList(myResponse);
                }
            }
            System.out.println("------------监听到了入参-------end----");
        } catch (Exception e) {
            System.out.println("-------------出错了-------------");
        }
        return null;
    }

    public static void end(Object targetMehod, Object request, Object response, String methodName) {

        try {
            System.out.println("-------------监听到了出参------start-----");
            Gson gson = new Gson();

            ColletExecutor executor = ColletExecutor.getInstance(CollectType.METHOD_COLLECT);
            JedisPool jedisPool = redisUtil.redisPoolFactory();
            Jedis resource = jedisPool.getResource();
            executor.executeTask(new ParamsAndReturnThread(gson.toJson(targetMehod), gson.toJson(request), gson.toJson(response), methodName, resource, "123||456"));
            System.out.println("-------------监听到了出参------ end -----");
        } catch (Exception e) {
            System.out.println("格式化出错了...." + e.getMessage());
        }
    }

    /**
     * 查询数据库获取响应
     * @param targetMethod      目标方法
     * @param requestHashCode   请求的hashcode值
     * @return
     */
    private static String getResult(String targetMethod, String requestHashCode) {

        MybatisSqlSessionFactory mybatisSqlSessionFactory = MybatisSqlSessionFactory.getMybatisSqlSessionFactory();
        SqlSessionFactory sqlSessionFactory = mybatisSqlSessionFactory.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            List<String> list = sqlSession.getMapper(AutoCollectMethodParamsMapper.class).selectByRequestHashCode(requestHashCode);
            if (list.size() > 0) {
                System.out.println("查到了" + list.get(0));
                //return list.get(0);
            }
        } finally {
            sqlSession.commit();
            sqlSession.close();
        }

        return null;
    }
    /**
     * 查询数据库获取响应
     * @param request
     * @return
     */
    private static String getResultOld(String targetMethod, String request) {

        Connection conn = null;
        Statement stmt = null;

        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://129.211.118.48:3306/postgirl?",
                    "czMysql",
                    "123456");
            stmt = conn.createStatement();

            String sql = "select response as RESP from auto_collect_method_params where request = '" + request + "' and ext1 = '" + targetMethod + "'";
            ResultSet resultSet = stmt.executeQuery(sql);
            Map<String,String> map = new HashMap<String,String>();
            while(resultSet.next()) {
                String key = resultSet.getString("RESP");
                if (key != null) {
                    return key;
                }
            }

        } catch (Exception e) {
            System.out.print(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.print("Can't close stmt/conn because of " + e.getMessage());
            }
        }

        return null;
    }

}
